// 获取参数
var fs = require("fs");
const path = require('path')

var stat=fs.stat;

var copy=function(src,dst){
    //读取目录
    fs.readdir(src,function(err,paths){
        console.log(paths)
        if(err){
            throw err;
        }
        paths.forEach(function(path){
            var _src=src+'/'+path;
            var _dst=dst+'/'+path;
            var readable;
            var writable;
            stat(_src,function(err,st){
                if(err){
                    throw err;
                }

                if(st.isFile()){
                    readable=fs.createReadStream(_src);//创建读取流
                    writable=fs.createWriteStream(_dst);//创建写入流
                    readable.pipe(writable);
                }else if(st.isDirectory()){
                    exists(_src,_dst,copy);
                }
            });
        });
    });
}

var exists=function(src,dst,callback){
    //测试某个路径下文件是否存在
    fs.exists(dst,function(exists){
        if(exists){//不存在
            callback(src,dst);
        }else{//存在
            fs.mkdir(dst,function(){//创建目录
                callback(src,dst)
            })
        }
    })
}

//递归创建目录 同步方法
function mkdirsSync(dirname) {

    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

module.exports = {
    // i 从1开始

    emptyDir(path){
        console.log('emptyDir:',path);
        function delDir(path){
            console.log('delDir',path)
            let files = [];
            if(fs.existsSync(path)){
                files = fs.readdirSync(path);
                console.log(files)
                files.forEach((file, index) => {
                    let curPath = path + "/" + file;
                    if(fs.statSync(curPath).isDirectory()){
                        delDir(curPath); //递归删除文件夹
                    } else {
                        fs.unlinkSync(curPath); //删除文件
                    }
                });
                console.log(path);
                fs.rmdirSync(path);
            }
        }

        delDir(path);
    },

    copyFile(path1,path2,callback) {
        // 拷贝文档
        let copyYuanMd = path1;
        let copyOverMd = path2;
        // 创建读取流
        let readableMd  = fs.createReadStream( copyYuanMd );
        // 创建写入流
        let writableMd  = fs.createWriteStream( copyOverMd );
        // 通过管道来传输流
        readableMd.pipe( writableMd );

        writableMd.on('close',function(){
            callback();
        });
    },
    // 同步创建文件夹
    mkdirsSync(dirpath) {
        mkdirsSync(dirpath)
    },
    // 拷贝文件
    copyDir(path1,path2) {
        exists(path1,path2,copy)
    }
};